



package com.znsd.study.controllor;

import java.io.BufferedInputStream;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.znsd.entitys.ClassInfo;
import com.znsd.entitys.CurriculumInfo;
import com.znsd.entitys.Cwj_ClassInfo;
import com.znsd.entitys.SpecialtyInfo;
import com.znsd.entitys.Users;

import com.znsd.exam.service.ExamPlanService;

import com.znsd.stu.service.Cwj_ClassService;
import com.znsd.study.service.CurriculumService;
import com.znsd.study.service.SpecialtyService;

@Controller
public class StudyControllor {

	@Autowired
	private ExamPlanService examPlanInfoService;
	@Autowired
	private SpecialtyService ss;
	@Autowired
	private CurriculumService cs;
	@Autowired
	private Cwj_ClassService cwj_ClassService;
	
	static Integer jia=0;
	
	@RequestMapping(value = "fidl",method = RequestMethod.GET)
	public String stuView() { 
		
		return "admin/field";
	}
	
	
	@RequestMapping(value = "teachercurr",method = RequestMethod.GET)
	public String teacherView() { 
		
		return "admin/teacherCurr";
	}
	//רҵ
	/*
	 * @ResponseBody 
	 * 
	 * @RequestMapping("/major.do") public List<Specialty> major() { List<Specialty>
	 * majorList = ss.majorList(); return majorList; } //�γ�
	 * 
	 * @ResponseBody
	 * 
	 * @RequestMapping("/curriculum") public List<Specialty> curriculum(String
	 * fId,HttpServletRequest request) { String dd=request.getParameter("fid");
	 * System.out.println("dd=="+dd); List<Specialty> currList = ss.currList(dd);
	 * return currList; } //�½�
	 * 
	 * @ResponseBody
	 * 
	 * @RequestMapping("/chapter") public List<Specialty> chapter(String
	 * fId,HttpServletRequest request) { String dd=request.getParameter("fid");
	 * List<Specialty> chapterList = ss.chapterList(dd); return chapterList; }
	 */
	
	//���β˵�
	@ResponseBody
	@RequestMapping("/tree.do") 
	public List<SpecialtyInfo> tree() 
	{ 
	  	List<SpecialtyInfo> tree = ss.treeList();
	  	System.out.println(tree.toString());
	  	return tree; 
	 }
	
	//���ݱ��
	@ResponseBody
	@RequestMapping("/datagrid") 
	public List<CurriculumInfo> currGrid(HttpServletRequest request) 
	{ 
		String cid=request.getParameter("cid");
		System.out.println("cid===="+cid);
		List<CurriculumInfo> currList = cs.currList(cid);
		for (CurriculumInfo curriculumInfo : currList) {
			System.out.println("==="+curriculumInfo.getUser().getUser_name());
		}
		
	  	return currList; 
	 }
	
	//教师的文件上传
	@RequestMapping("/upload")
    @ResponseBody
    public String upload(HttpServletRequest  request, 
    		@RequestParam("wen") String wen,
    		@RequestParam("file") MultipartFile file,
    		@RequestParam("jj") String jj,
    		@RequestParam("kongjian") String kongjian) throws Exception {
		
        System.out.println("=="+wen);//命名的文件名称
        System.out.println("=="+jj);//父类的Id
        System.out.println("=="+kongjian);//是否是私人空间
        HttpSession session = request.getSession();
        Users user =(Users) session.getAttribute("user");
        System.out.println("=="+user.getUser_id());//教师的Id
        System.out.println("创建时间=="+new Date());//上传的时间
        
        //截取一下私人空间的值
        	//String siren=kongjian.substring(kongjian.lastIndexOf(","));
        	
        	
        	String[] s=kongjian.split(",");
        	String siren=s[0];
        	System.out.println(s[0]);
        System.out.println("siren=="+siren);
        jia++;
        wen+="("+ jia +")";
        
        
        //如果文件不为空，写入上传路径
        if(!file.isEmpty()) {
            //上传文件路径
            String path = request.getServletContext().getRealPath("target/uploads");
            
            System.out.println("······························"+path); 
            //上传文件名
            String filename = file.getOriginalFilename();
            
            
            //截取文件后缀名
            String fileext = filename.substring(filename.lastIndexOf("."));
            wen+=fileext;
            File filepath = new File(path,wen);
            
            System.out.println("类型-------------------"+fileext);
            //判断是否是允许上传的文件类型
            if (!(fileext.equals(".rar")||fileext.equals(".zip")||fileext.equals(".tar"))) {
				return "3";
			}
            
            //判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            
            
            
            //将上传文件保存到一个目标文件当中
            file.transferTo(new File(path + File.separator + wen));
            
            String url=path + File.separator + wen;
            
          //输出文件上传最终的路径 测试查看
            System.out.println("最终路径------------------------------"+path + File.separator + wen);
            
            CurriculumInfo curr=new CurriculumInfo();
            curr.setUpload_state(fileext);//上传类型
            curr.setPerson_state(Integer.parseInt(siren));//是否是公开
           
            curr.setUser(user);//教师Id
            curr.setCurriculum_createtime(new Date());//创建时间
            curr.setUrl(url);//上传路径
            curr.setCurriculum_del(0);//是否是删除状态
            curr.setSuperor(Integer.parseInt(jj));//父类ID
            curr.setCurriculum_name(wen);//教程名称
            
            long addCurr = cs.addCurr(curr);
            if (addCurr>0) {
            	return "1";
			}
           return "2";
        } else {
            return "0";
        }
 
	}
	
	
	//学生的文件下载
	@RequestMapping(value="/download",method=RequestMethod.GET)
    public void download(
    		@RequestParam(value="filename")String filename,
    		@RequestParam(value="filetype")String fileType,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {
         
        String path = request.getServletContext().getRealPath("target/uploads"); 
        
        File file=new File(path+"/"+filename);
        //获取输入流  
        InputStream bis = new BufferedInputStream(new FileInputStream(file));
        
        response.setContentType(fileType);
        response.setContentLength((int)file.length());
        filename = URLEncoder.encode(filename,"UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        //转码，免得文件名中文乱码  
          
        //设置文件下载头  
           
        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型    
           
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        
        IOUtils.copy(bis,out);
        
        out.close();
        bis.close();
    }
	
	//全部的上传记录
	@ResponseBody
	@RequestMapping("/getListcurrdatagrid") 
	public Map<String ,Object> getListCurr(@Param("sou")String sou,Integer page,Integer rows) 
	{ 
		if (sou==null || sou.equals("")) {
			
			
			
			List<CurriculumInfo> currList = cs.getListCurr((page-1)*rows,rows);
			long total = cs.currCount();
			
			Map<String, Object> result = new HashMap<String, Object>();  
	        result.put("total", total);  
	        result.put("rows", currList);
	        result.put("page", page);
			
		  	return result; 
		}
		List<CurriculumInfo> currList = cs.souListCurr(sou, (page-1)*rows, rows);
		long total = cs.souCurrCount(sou);
		
		Map<String, Object> result = new HashMap<String, Object>();  
        result.put("total", total);  
        result.put("rows", currList);
        result.put("page", page);
		
	  	return result;
	 }
	
	//单人上传记录
	@ResponseBody
	@RequestMapping("/getsinglelistcurr") 
	public Map<String ,Object> getSingleListCurr(String grsou,Integer page,Integer rows,HttpServletRequest request) 
	{ 
		System.out.println("传过来的值===="+grsou);
		
		Users user =(Users) request.getSession().getAttribute("user");
		Integer user_id = user.getUser_id();
		
		if (grsou==null || grsou.equals("")) {
			List<CurriculumInfo> currList = cs.getSingleListCurr(user_id, (page-1)*rows, rows);
			
			System.out.println("我 是 个 空");
			long total = cs.currSingCount(user_id);
			System.out.println("------"+total);
			
			Map<String, Object> result = new HashMap<String, Object>();  
	        result.put("total", total);  
	        result.put("rows", currList);
	        result.put("page", page);
			
		  	return result; 
		}
		List<CurriculumInfo> singleCurrSou = cs.getSingleCurrSou(grsou,user_id, (page-1)*rows, rows);
		long currSingCountSou = cs.currSingCountSou(grsou, user_id);
		Map<String, Object> result = new HashMap<String, Object>();  
        result.put("total", currSingCountSou);  
        result.put("rows", singleCurrSou);
        result.put("page", page);
		
	  	return result; 
	 }
	
	//删除教程的方法
	@ResponseBody
	@RequestMapping("/delcurrioulum")
	public String delCurrioulum(@Param("id")Integer id) {
		long delCurr = cs.delCurr(id);
		if (delCurr > 0) {
			return "1";
		}
		return "2";
	}

	//还原教程的方法
	@ResponseBody
	@RequestMapping("/huancurr")
	public String huanCurrioulum(@Param("id")Integer id) {
		long huanCurr = cs.huanCurr(id);
		if (huanCurr > 0) {
			return "1";
		}
		return "2";
	}

	//班级的下拉框
	@ResponseBody
	@RequestMapping("/clazzlist")
	public List<ClassInfo> clazList() {
		List<ClassInfo> classes = examPlanInfoService.getClasses(null);
		System.out.println("------班级-------"+classes.toString());
		return classes;

}
	@ResponseBody
	@RequestMapping(value = "combo")
	public List<Map<String, Object>> combo(HttpServletRequest request){
		HttpSession session = request.getSession();
		Users user = (Users) session.getAttribute("user");
		List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
		
		List<Cwj_ClassInfo> clazz = cwj_ClassService.getByTeacherId(user.getUser_id());
		Map<String, Object> m=new HashMap<String, Object>();
		m.put("id", 0);
		m.put("text", "--请选择--");
		list.add(m);
		for (Cwj_ClassInfo c : clazz) {
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("id", c.getSpecialty().getSpecialty_id());
			map.put("text", c.getClazz_name());
			list.add(map);
		}
		
		return list; 

	}
	
	/*
	 * @ResponseBody
	 * 
	 * @RequestMapping public Map<String, Object> loadtable(String id){ Map<String,
	 * Object> map=new HashMap<String, Object>(); if("0".equals(id)||id==null) {
	 * map.put("data", null); map.put("html1", null); return map; }
	 * List<SpecialtyInfo> list = ss.queryPid(id); StringBuffer sb=new
	 * StringBuffer(); sb.append("<table>"); for (SpecialtyInfo sp : list) {
	 * sb.append("<tr>"); sb.append("<td>");
	 * sb.append("<input type='checkbox' name='mj' vale='"+sp.getSpecialty_id()+"'>"
	 * +sp.getSpecialty_name()); sb.append("</td>"); sb.append("</tr>"); }
	 * sb.append("</table>"); map.put("data", list); map.put("html1", sb); return
	 * map; }
	 */
}
